package com.shiro.credentialsMatcher;

/**
 * @author WxrStart
 * @create 2022-05-25 14:41
 */
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.shiro.token.JWTToken;
import com.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;

@Slf4j
public class JwtCredentialsMatcher implements CredentialsMatcher {


    /**
     * JwtCredentialsMatcher只需验证JwtToken内容是否合法
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
        log.info("JwtCredentialsMatcher的doCredentialsMatch调用了");
//        String token = authenticationToken.getCredentials().toString();
//        String email = JWTUtils.getClaimFiled(token,"email");
//        try {
//            Algorithm algorithm = Algorithm.HMAC256(JWTUtils.SECRET);
//            JWTVerifier verifier = JWT.require(algorithm).withClaim("email", email).build();
//            verifier.verify(token);
//            return true;
//        } catch (JWTVerificationException e) {
//            log.error(e.getMessage());
//        }
//        return false;
//    }
        JWTToken jwtToken=(JWTToken)authenticationToken;
        String token = jwtToken.getCredentials();

        if(JWTUtils.getClaimFiled(token,"email")==null){
            log.error("token payload异常");
            throw new AuthenticationException("token payload异常");
        }
        if(JWTUtils.getClaimFiled(token,"userRole")==null){
            log.error("token payload异常");
            throw new AuthenticationException("token payload异常");
        }
        if(JWTUtils.isTokenExpired(token)){
            log.error("token已过期，请重新登录");
            throw new AuthenticationException("token已过期，请重新登录");
        }
        String email = JWTUtils.getClaimFiled(token, "email");
        String userRole = JWTUtils.getClaimFiled(token, "userRole");
        if(!JWTUtils.verify(token,email,userRole,JWTUtils.SECRET)){
            throw new AuthenticationException("token其他异常");
        }
        return true;


    }

}